<template>
  <n-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    size="small"
    label-placement="left"
    label-width="80px">
    <n-grid :cols="12" :x-gap="24">
      <n-form-item-gi :span="12" label="包名" path="packages">
        <n-input
          v-model:value="formData.packages"
          placeholder="以英文句号分隔" />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="模块名" path="module">
        <n-input v-model:value="formData.module" placeholder="以英文句号分隔" />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="表名前缀" path="tablePrefix">
        <n-input
          v-model:value="formData.tablePrefix"
          placeholder="设定后生成的类名将自动去除该前缀" />
      </n-form-item-gi>
    </n-grid>
  </n-form>
</template>

<script lang="ts" setup>
import type { FormInst, FormRules } from "naive-ui";
import { generateCode } from "@/api";
import { context } from "@/storage/context";

const formData = ref<{
  packages?: string;
  module?: string;
  tablePrefix?: string;
}>({
  packages: context.getDefaultPkg(),
});
const formRules: FormRules = {
  packages: { required: true, message: "请输入包名" },
  module: { required: true, message: "请输入模块名" },
};

const formRef = ref<FormInst>();
const handleGenCode = async (menuOption: MenuOption, tables: TableInfo[]) => {
  await formRef.value?.validate();
  await generateCode(menuOption.target.info, menuOption.label!, {
    ...formData.value,
    tables: JSON.stringify(tables),
  });

  context.setDefaultPkg(formData.value.packages!);
};

defineExpose({ handleGenCode });
</script>
